package dk.itu.spvc.tourtracker.gui;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import dk.itu.spvc.tourtracker.model.CurrentState;
import dk.itu.spvc.tourtracker.model.JSONServerResponse;
import dk.itu.spvc.tourtracker.model.Note;
import dk.itu.spvc.tourtracker.model.Point;
import dk.itu.spvc.tourtracker.model.PointType;
import dk.itu.spvc.tourtracker.model.ResponseListener;
import dk.itu.spvc.tourtracker.model.Trip;
import dk.itu.spvc.tourtracker.service.ServiceLocalSQL;
import dk.itu.spvc.tourtracker.service.ServiceRemoteSQL;

public class UploadActivity extends Activity implements OnClickListener, ResponseListener {

	// PRIVATE FIELDS

	// Debug
	private static final String TAG = "TourTracker";
	private static final boolean D = true;

	private ServiceRemoteSQL srvc_remote = ServiceRemoteSQL.getService();
	private ServiceLocalSQL srvc_local = ServiceLocalSQL.getService(this);
	private CurrentState currentState;

	// OVERRIDES

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload);
	}

	@Override
	protected void onStart() {
		super.onStart();

		((Button) findViewById(R.id.UploadButton)).setOnClickListener(this);
		// ((Button) findViewById(R.id.CancelButton)).setOnClickListener(this);

		currentState = srvc_local.getCurrentState();

		if (currentState == null) {
			// Cancel upload if no state - should never happen
			this.setResult(RESULT_CANCELED);
			finish();
		}

	}

	// BUTTON HANDLING

	public void onClick(View v) {

		if (v == findViewById(R.id.UploadButton)) {
		
			String formated = getFormatedJSON();			
			srvc_remote.uploadTrip(formated, this);
			Log.d(TAG, formated);

		}
	}

	public void onResponseReceived(HttpResponse response) {

		if (response != null) {

			JSONServerResponse res = new JSONServerResponse(response);

			if (!res.hasError()) {

				if (res.getAction().contentEquals("upload_trip")) {

					HashMap<Integer, Integer> mappings = res.getMappedTrips();

					if (mappings != null) {

						for (Entry<Integer, Integer> entry : mappings.entrySet()) {
							Trip trip = srvc_local.getTrip(entry.getKey());
							srvc_local.updateTrip(trip.getTripId(), entry.getValue(), trip.getTripName());
						}
						
						Toast.makeText(getBaseContext(), res.getMessage(), Toast.LENGTH_SHORT).show();

					}

				}

				this.setResult(RESULT_OK);
				finish();
			} else {
				Toast.makeText(getBaseContext(), res.getMessage(), Toast.LENGTH_SHORT).show();
			}

		} else {
			Toast.makeText(getBaseContext(), "Connection problem.", Toast.LENGTH_SHORT).show();
		}

	}

	public String getFormatedJSON() {

		JSONArray _trips = new JSONArray();
		
		List<Trip> trips = srvc_local.getTrips(true);		

		for (Trip trip : trips) {

			JSONObject _trip = new JSONObject();
			JSONArray _pathPoints = new JSONArray();
			JSONArray _pinPoints = new JSONArray();
			
			List<Point> pathPoints = srvc_local.getPoints(trip.getTripId(), PointType.PATH);
			List<Point> pinPoints = srvc_local.getPoints(trip.getTripId(), PointType.PIN);

			try {

				_trip.put("trip_id", trip.getTripId());
				_trip.put("trip_name", trip.getTripName());

				for (Point p : pathPoints) {

					JSONArray pathPoint = new JSONArray();
					pathPoint.put(p.getLongitude());
					pathPoint.put(p.getLatitude());

					_pathPoints.put(pathPoint);

				}

				_trip.put("path_points", _pathPoints);

				for (Point p : pinPoints) {

					List<Note> notes = srvc_local.getNotes(p.getPointId());

					JSONArray pinPoint = new JSONArray();
					pinPoint.put(p.getLongitude());
					pinPoint.put(p.getLatitude());
					if (notes.size() > 0)
						pinPoint.put(notes.get(0).getText());
					_pinPoints.put(pinPoint);

				}

				_trip.put("pin_points", _pinPoints);
				_trips.put(_trip);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return _trips.toString();
	}

}
